﻿using XinLife.Core.Extention;
using XinLife.Core.Helper;

namespace XinLife.Common.Setup
{
    public static class CorsSetup
    {
        /// <summary>
        /// Cors 启动服务
        /// </summary>
        public static void AddCorsSetup(this IServiceCollection services)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));

            services.AddCors(c =>
            {
                if (!Appsettings.app("AllowOrigins").IsEmpty())
                {
                    c.AddPolicy("Cors",
                        policy =>
                        {
                            policy.WithOrigins(Appsettings.app("AppSetting", "AllowOrigins")!.Split(','))
                                   .AllowAnyHeader()
                                   .AllowAnyMethod();
                        });
                }
                else
                {
                    //允许任意跨域请求
                    c.AddPolicy("Cors",
                        policy =>
                        {
                            policy
                            .SetIsOriginAllowed((host) => true)
                            .AllowAnyMethod()
                            .AllowAnyHeader()
                            .AllowCredentials();
                        });
                }
            });
        }
    }
}
